#include "I_BaseLib.h"

GDI_FRAME_BUFFER::~GDI_FRAME_BUFFER() 
{
	if (theDIB)
	{
		DeleteObject(theDIB);
		theDIB = 0;
	}
	if (backbuffer)
	{
		delete[] backbuffer;
		backbuffer = 0;
	}
	if (thepixels)
	{
		delete[] thepixels;
		thepixels = 0;
	}
 
}

GDI_FRAME_BUFFER::GDI_FRAME_BUFFER(int w, int h)
{

	width=w;
	height=h;

	//DIB data
	bmi.bmiHeader.biSize            = sizeof(BITMAPINFOHEADER);
	bmi.bmiHeader.biWidth           = width; 
	bmi.bmiHeader.biHeight          = -height;
	bmi.bmiHeader.biPlanes          = 1;
	bmi.bmiHeader.biBitCount        = 24; //true color
	bmi.bmiHeader.biCompression     = 0;
	bmi.bmiHeader.biSizeImage       = 0;
	bmi.bmiHeader.biXPelsPerMeter   = 0;
	bmi.bmiHeader.biYPelsPerMeter   = 0;
	bmi.bmiHeader.biClrUsed         = 0;
	bmi.bmiHeader.biClrImportant    = 0;

	hdc = CreateCompatibleDC(0);
	theDIB = CreateDIBSection(::GetDC(0),&bmi,DIB_RGB_COLORS,&thepixels,0,0);
	SelectObject(hdc,theDIB);

	backbuffer = new COLOR[width*height];
	for (int y=0;y<height;y++)
		for (int x=0;x<width;x++)
			backbuffer[x+y*width]=COLOR(0,0,0);
			
}

void GDI_FRAME_BUFFER::PutPixel(COLOR col,int x, int y)
{
	if (x<width && x>0 && y<height && y>0)
	{
		static_cast<COLOR*>(thepixels)[(width*y)+x]=col;
	}
}

void GDI_FRAME_BUFFER::PutPixelAlpha(COLOR col,int x, int y,float alpha)
{
	
	if (x<width && x>0 && y<height && y>0)
	{
		int index = (width*y)+x;
		static_cast<COLOR*>(thepixels)[index] = (static_cast<COLOR*>(thepixels)[index])*(1-alpha) + (col)*alpha;
	}
}

COLOR GDI_FRAME_BUFFER::GetPixel(int x, int y)
{
	if (x<width && x>0 && y<height && y>0)
	{
		return static_cast<COLOR*>(thepixels)[(width*y)+x];
	}
	else
	{
		return COLOR();
	}
}

void GDI_FRAME_BUFFER::Clear()
{
	
	memcpy(thepixels,backbuffer,width*height*3);
	hWnd = GetActiveWindow();
	InvalidateRgn(hWnd,0,false);
	mainHdc = BeginPaint( hWnd, &ps );

}

void GDI_FRAME_BUFFER::Draw()
{

	BitBlt(mainHdc,0,0,width,height,this->hdc,0,0,SRCCOPY);	
	EndPaint (hWnd, &ps);
}
 
void GDI_FRAME_BUFFER::BlitMem(int x, int y, int w, int h, void* buffer)
{
	
	int position_offset = (y*width + x)*3;

	for (int i=0;i<h;i++)
	{
		memcpy(((char*)thepixels)+width*3*i+position_offset, ((char*)buffer)+w*3*(h-i-1),w*3); //copy 3 bytes at ones (framebuffer compatibility)
	}

}
